﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Routing;
using Sharp.Infrastructure;
using Sharp.Infrastructure.IoC;
using Sharp.Platform.Interface;

namespace Sharp.Platform.Mvc
{
    public class TemplateMange
    {
        private static readonly TemplateOperateAction oa = new TemplateOperateAction();

        static TemplateMange()
        {
            var provider = ServiceLocator.Instance.GetService<ITemplateProvider>();


            oa.GatherOperate("Create", provider.Create);
            oa.GatherOperate("Details", provider.Details);
            oa.GatherOperate("Edit", provider.Edit);
            oa.GatherOperate("Index", provider.Index);

            string tempfile = WebServer.MapPath("~/Views/Temp/");
            if (!Directory.Exists(tempfile))
            {
                Directory.CreateDirectory(tempfile);
            }
        }

        /// <summary>
        /// 获取模板
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetViewTemplate(RequestContext requestContext, object model)
        {
            var area = Convert.ToString(requestContext.RouteData.DataTokens["area"]);
            var controller = requestContext.RouteData.Values["Controller"].ToString();
            var action = requestContext.RouteData.Values["Action"].ToString();
            string key;
            if (area.IsNullOrEmpty())
            {
                key = $"{controller}_{action}";
            }
            else
            {
                key = $"{area}_{controller}_{action}";
            }

            var viewPath = HttpRuntime.Cache.Get(key) as string;//如果视图的缓存存在，说明Model没有修改。


            if (!viewPath.IsNullOrEmpty() && File.Exists(WebServer.MapPath(viewPath)))
            {
                return viewPath;
            }
            else
            {
                string tempfile = "~/Views/Temp/" + key + ".cshtml";

                string html = oa.ExecuteOperate(action, model);
                File.WriteAllText(WebServer.MapPath(tempfile), html, Encoding.UTF8);

                HttpRuntime.Cache.Add(key, tempfile, null, DateTime.Now.AddSeconds(3600), TimeSpan.Zero, CacheItemPriority.NotRemovable, null);


                return tempfile;
            }
        }
    }
}
